﻿using System;
using System.IO;

namespace Azure.Online.Proxy.Server {
    public class HttpServerRequest : HttpServerMessage {
        private readonly HttpServerContext _context;
        private readonly Stream _stream;
        private Stream _inputStream;

        public HttpServerRequest(HttpServerContext context, Stream stream)
        {
            _context = context;
            _stream = stream;
        }

        public string Verb { get; set; }

        public string Path { get; set; }

        public string Version { get; set; }

        public string Host {
            get { return Headers["Host"]; }
        }

        public Uri Url {
            get {
                return new Uri("http://" + Host + Path);
            }
        }

        public Stream InputStream {
            get {
                if (_inputStream == null) {
                    if (SendChunked) {
                        _inputStream = new HttpServerChunkedRequestStream(_context, _stream);
                    } else {
                        _inputStream = new HttpServerRequestStream(_context, _stream, ContentLength.Value);
                    }
                }
                return _inputStream;
            }
        }

        private Uri _cachedUri;
        private QueryDictionary _cachedQuery;

        public QueryDictionary QueryString {
            get {
                if (_cachedUri != Url) {
                    _cachedQuery = new QueryDictionary(Url);
                    _cachedUri = Url;
                }
                return _cachedQuery;
            }
        }
    }
}
